package com.example.pageexample.page;

import android.util.Log;

import androidx.annotation.NonNull;
import androidx.paging.PageKeyedDataSource;

import com.example.pageexample.database.Picture;
import com.example.pageexample.database.PictureHelper;

import io.reactivex.rxjava3.schedulers.Schedulers;

/**
 * 分页处理数据逻辑。注意数据加载需要在子线程进行
 * @author mailanglideguozhe
 * @date 2021-6-22
 */
public class PageSource extends PageKeyedDataSource<Integer , Picture> {
    private static final String TAG = "PageSource";
    /**
     * 页码从0开始
     */
    private int FIRST_PAGE = 0;

    /**
     * 加载首页的数据
     * @param params 加载的参数
     * @param callback 用于回调结果的callback
     */
    @Override
    public void loadInitial(@NonNull LoadInitialParams<Integer> params, @NonNull LoadInitialCallback<Integer, Picture> callback) {
        Log.d(TAG,"initial page = "+ FIRST_PAGE);
        Schedulers.computation().scheduleDirect(new Runnable() {
            @Override
            public void run() {
                PictureHelper pictureHelper = PictureHelper.getInstance();
                pictureHelper.getData(FIRST_PAGE *Constants.PAGE_SIZE,Constants.PAGE_SIZE,callback, FIRST_PAGE +1);
            }
        });

    }

    /**
     * 加载前一页数据，注意仅在有前一页数据时调用数据请求
     * @param params 加载的参数
     * @param callback 用于回调结果的callback
     */
    @Override
    public void loadBefore(@NonNull LoadParams<Integer> params, @NonNull LoadCallback<Integer, Picture> callback) {
        Log.d(TAG,"before page = "+ (params.key - 1));
        Schedulers.computation().scheduleDirect(new Runnable() {
            @Override
            public void run() {
                if(params.key > 0){
                    PictureHelper pictureHelper = PictureHelper.getInstance();
                    pictureHelper.getData(params.key, Constants.PAGE_SIZE,callback,params.key - 1);
                }
            }
        });
    }

    /**
     *加载下一页数据，注意仅在有下一页数据时调用数据请求
     * @param params 加载的参数
     * @param callback 用于回调结果的callback
     */
    @Override
    public void loadAfter(@NonNull LoadParams<Integer> params, @NonNull LoadCallback<Integer, Picture> callback) {
        Log.d(TAG,"after page = "+ params.key);
        FIRST_PAGE++;
        Schedulers.computation().scheduleDirect(new Runnable() {
            @Override
            public void run() {
                PictureHelper pictureHelper = PictureHelper.getInstance();
                if(pictureHelper.hasNextPage(params.key)){
                    int nextKey = params.key+1;
                    pictureHelper.getData(params.key, Constants.PAGE_SIZE,callback, nextKey);
                }
            }
        });
    }
}
